// miniprogram/pages/sendInfo/sendInfo.js
const db = wx.cloud.database(); // 初始化数据库
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],
    address: '',
    dec: '',
    latitude: '',
    longitude: '',
    fileids: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.getAddressDetail()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 开始拍照
  uploadImg: function () {
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths
        let arr = []
        for (let i in tempFilePaths) {
          arr.push(new Promise((reslove, reject) => {
            const imgUrl = tempFilePaths[i]
            const suffix = /\w+$/.exec(imgUrl)[0]
            console.log('push', imgUrl)
            wx.cloud.uploadFile({
              // 指定上传到的云路径
              cloudPath: new Date().getTime() + 'warning.' + suffix,
              // 指定要上传的文件的小程序临时文件路径
              filePath: imgUrl,
              // 成功回调
              success: res => {
                reslove(res)
              },
              fail: err => {
                reject(err)
              }
            })
          }))
        }
        wx.showLoading({
          title: '正在上传',
        })
        Promise.all(arr).then(res => {
          const newData = res.map(v => v.fileID)
          this.setData({
            fileids: newData
          })
          wx.hideLoading()
        }).catch(
          err => {
            console.log(err, '上传失败')
          }
        )
      }
    })
  },
  
  // 提交
  submit: async function () {
    wx.showLoading({
      title: '正在提交',
    })
    const {
      address,
      dec,
      longitude,
      latitude,
      fileids
    } = this.data
    
    if (fileids.length === 0) {
      this.errMessage('请选择图片')
      return
    }
    if (!address || !longitude || !latitude) {
      this.errMessage('请选择并填写问题发生地')
      return
    }
    if (!dec) {
      this.errMessage('请填写问题描述')
      return
    }
    const submitData = {
      address: this.data.address,
      dec: this.data.dec,
      location: [ this.data.longitude, this.data.latitude ],
      fileids: this.data.fileids
    }
    // 云函数
    wx.cloud.callFunction({
      name: 'postwarn',
      data: submitData,
      success: result => {
        console.log(result, 'success')
        wx.hideLoading()
        wx.redirectTo({
          url: '/pages/tipPage/tipPage?page=2'
        })
      },
      fail: err => {
        console.log(err)
        this.errMessage('发布失败')
      }
    })
  },

  // 获取位置
  getCurLocation: function () {
    this.getSetting(() => {
      wx.chooseLocation({
        success: res => {
          const {name, address, latitude, longitude} = res
          this.setData({
            address: name + address,
            latitude: latitude,
            longitude: longitude
          })
        },
        fail: err => {
          console.log(err)
        }
      })
    })
  },

  // 位置授权
  getSetting: function (callback) {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userLocation']) {
          callback()
        } else {
          this.errMessage('无法获取位置信息')
        }
      },
      fail: err => {
        this.errMessage(err)
      }
    })
  },

  errMessage: function (title = '', duration = 2000) {
    wx.showToast({
      title,
      icon: 'none',
      duration
    })
  },
  // 点击图片查看
  showImg: function (e) {
    const current = e.currentTarget.dataset.url
    const urls = this.data.fileids
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  // 地址描述
  bindAddressBlur: function ({ detail }) {
    this.setData({
      address: detail.value
    })
  },

  // 问题描述
  bindDecBlur: function ({ detail }) {
    this.setData({
      dec: detail.value
    })
  }
})